/*
	This file is part of SRServerLibrary.
	Foobar is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	SRServerLibrary is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with SRServerLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "MBBrowser.h"
//#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "sys/stat.h"

using namespace std;

MBBrowser::MBBrowser(char *rootDir)
{
	//validMediaExtensions.push_back("avi");
	MBItem rootItem = MBItem(rootDir, "");
	open(rootItem);
}


vector<MBItem> MBBrowser::open(MBItem item)
{
	if(!item.isDirectory()) // it is a file. open it
	{
		// asd
	}
	else
	{
		const char *dir = item.getAbsolutePath().c_str(); // for now
		const char *currentDirPath = item.getAbsolutePath().c_str();
		struct dirent *entry;
		DIR *d;
	
		char *currentItem;
		struct stat currentItemStat;
	

		if (!(d = opendir(dir)))
		{
			cout << "error: could not open directory";
			return vector<MBItem>();
		}
	
		while (entry = readdir(d))
		{
			if (entry->d_name[0] == '.')
			{
				cout << "ignoring item" << endl;
				continue;
			}
		
			// check whether the item is a directory or not
			currentItem = (char*)malloc(strlen(currentDirPath)+strlen(entry->d_name)+2);
			if(currentItem == NULL)
			{
				cout << "COULD NOT ALLOCATE MEMORY :(:(" << endl;
				return vector<MBItem>();
			}
		
			currentItem[0] = '\0';
			strcpy(currentItem, currentDirPath);
			strcat(currentItem, "/");
			strcat(currentItem, entry->d_name);
			cout << "currentItem: " << currentItem << endl;
		
			stat((const char*)currentItem, &currentItemStat);
		
			// create MBItem objects here
		
			cout << endl;
		
			// free memory
			free(currentItem);
		}
	
		closedir(d);
	}
}